package cn.mengfly.fxtest.app.urltest;

import javafx.application.Platform;
import lombok.Getter;

import java.util.*;
import java.util.function.Consumer;

/**
 * @author Mengfly
 */
public class Notifications {

    public final static String EVENT_MODEL_UPDATE = "modelUpdate";

    private final Map<String, List<SubscriberObject>> subscriptions = new LinkedHashMap<>();

    private static final Notifications INSTANCE = new Notifications();

    public void publish(String event) {
        Platform.runLater(() -> {
            List<SubscriberObject> subscribeObjectList = INSTANCE.subscriptions.get(event);
            if (subscribeObjectList != null) {
                subscribeObjectList.forEach(obj -> obj.getCb().accept(event));
            }
        });
    }

    public void subscribe(String event, Object subscriber, Consumer<String> cb) {
        if (!INSTANCE.subscriptions.containsKey(event)) {
            INSTANCE.subscriptions.put(event, new ArrayList<>());
        }

        INSTANCE.subscriptions.get(event).add(new SubscriberObject(subscriber, cb));
    }

    public void unsubscribe(String event, Object subscriber) {
        List<SubscriberObject> subscriberObjects = INSTANCE.subscriptions.get(event);
        if (subscriberObjects != null) {
            subscriberObjects.remove(subscriber);
        }
    }


    @Getter
    public static class SubscriberObject {
        private final Object subscriber;
        private final Consumer<String> cb;


        public SubscriberObject(Object subscriber, Consumer<String> cb) {
            this.subscriber = subscriber;
            this.cb = cb;
        }

        @Override
        public boolean equals(Object o) {
            return subscriber.equals(o);
        }

        @Override
        public int hashCode() {
            return Objects.hash(subscriber);
        }
    }
}
